<?php
/**
 * User Controller
 *
 * @author     Olivier Parent
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent
 */
class UserController extends Zend_Controller_Action
{

    public function init()
    {
        $view = $this->view;
        $view->placeholder('baseUrlStyles')->set( $view->baseUrl('styles/') );
    }

    /**
     * Wordt uitgevoerd voordat een Action uitgevoerd wordt.
     */
    public function preDispatch()
    {
        // Stuur de ingelogde gebruiker naar de homepagina, tenzij er uitgelogd wordt.
        if ( Zend_Auth::getInstance()->hasIdentity() ) {
            switch ( $this->getRequest()->getActionName() ) {
                case 'add':
                    break;
                case 'details':
                    break;
                case 'logout':
                    break;
                case 'registration':
                    break;
                case 'search':
                    break;
                default:
                    $this->_helper->redirector('index', 'index');
                    break;
            }
        } else {
            // Uitloggen kan niet als je niet uitgelogd bent.
            switch ( $this->getRequest()->getActionName() ) {
                case 'logout':
                    $this->_helper->redirector('index');
                    break;
                default:
                    break;
            }
        }
    }

    public function indexAction()
    {
        $translate = Zend_Registry::get('Zend_Translate');

        $view = $this->_getView('page_title_user_login');
        $view->form = $this->_getLoginForm();
        $view->goto = sprintf( $translate->_('link_goto'), $translate->_('page_title_user_register') );
    }

    public function authAction()
    {
        $translate = Zend_Registry::get('Zend_Translate');

        $request = $this->getRequest();

        $view = $this->_getView('page_title_user_login_error');

        $form = $this->_getLoginForm();

        // Formulier valideren
        if ( !$form->isValid( $request->getPost() ) ) {
            $view->form = $form;
            $view->goto = sprintf( $translate->_('link_goto'), $translate->_('page_title_user_register') );
            return $this->render('index'); // Render index view script
        }

        // Gebruikersauthentificatie
        $values = $form->getValues();
        $adapter = $this->_getAuthAdapter($values);
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        if ( !$result->isValid() ) {
            $form->setDescription( $translate->_('form_error_login') );
            $view->form = $form;
            $view->goto = sprintf( $translate->_('link_goto'), $translate->_('page_title_user_register') );
            return $this->render('index'); // Render index view script
        } else {
            $storage = $auth->getStorage();
            $storage->write( $adapter->getResultRowObject(array(
                'user_role',
                'user_givenname',
                'user_familyname',
            )));
        }

        return $this->_helper->redirector('index');
    }

    public function detailsAction()
    {
        $translate = Zend_Registry::get('Zend_Translate');

        //$autocomplete = new ZendX_JQuery_Form_Element_AutoComplete('autocomplete');
        //$autocomplete->setLabel('form_input_label_email');
        //$view->autocomplete = $autocomplete->setJQueryParam('data', array('olivier.parent@arteveldehs.be') );
        //$view->autocomplete = $autocomplete->setJQueryParam('source', $view->baseUrl('user/search') );
        
        $view = $this->_getView('page_title_user_details');
        
        $form = $this->_getDetailsForm();
        $form->getElement('email')->setJQueryParam('source', $view->baseUrl('user/search') );
        $request = $this->getRequest();
        // Formulier valideren
        if ( $request->isPost() ) {
            if ( $form->isValid( $request->getPost() ) ) {
                $email = $form->getValue('email');
                $userMapper = new Application_Model_UserMapper();
                $user = $userMapper->fetchByEmail($email); 
                #Zend_Debug::dump($user);
                if ( $user->Id !== null ) {
                    $view->details = "{$user->Id}. {$user->Givenname} {$user->Familyname} ({$user->Email})";
                }

            }
        }
        
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
        $view->form = $form;
        $view->goto = sprintf( $translate->_('link_goto'), $translate->_('page_title_user_register') );
    }

    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();

        return $this->_helper->redirector('index');
    }

    public function registrationAction()
    {
        $translate = Zend_Registry::get('Zend_Translate');

        $view = $this->_getView('page_title_user_register');
        $view->form = $this->_getRegistrationForm();
        $view->goto = sprintf( $translate->_('link_goto'), $translate->_('page_title_user_login') );
    }

    public function addAction()
    {
        $translate = Zend_Registry::get('Zend_Translate');
        $request = $this->getRequest();

        $view = $this->_getView('page_title_user_add_error');

        // Formulier valideren
        $form = $this->_getRegistrationForm();
        if ( !$form->isValid( $request->getPost() ) ) {
            $view->form = $form;
            $view->goto = sprintf( $translate->_('link_goto'), $translate->_('page_title_user_login') );
            return $this->render('registration'); // Render registration view script
        }

        // Gebruiker toevoegen
        $values     = $form->getValues();
        $user       = new Application_Model_User($values);
        $userMapper = new Application_Model_UserMapper();
        $userMapper->save($user);

        return $this->_helper->redirector('index');
    }

    public function searchAction()
    {
        $this->_helper->layout()->disableLayout(); // Layout uitschakelen
        $this->_helper->viewRenderer->setNoRender(true);

        $userMapper = new Application_Model_UserMapper();
        $users = $userMapper->fetchAllByEmail($this->_getParam('term'));

        #Zend_Debug::dump($users);
        $result = array();
        foreach ($users as $user) {
            $result[] = $user->Email;
        }
        
        $this->_helper->json($result);
    }

   /**
     * @return Application_Form_Registration
     *
     */
    private function _getDetailsForm()
    {
        return new Application_Form_Details(array(
            'action' => $this->view->baseUrl('user/details'),
            'method' => 'post',
        ));
    }
    
    /**
     * @return Application_Form_Login
     *
     */
    private function _getLoginForm()
    {
        return new Application_Form_Login(array(
            'action' => $this->view->baseUrl('user/auth'),
            'method' => 'post',
        ));
    }

    /**
     * @return Application_Form_Registration
     *
     */
    private function _getRegistrationForm()
    {
        return new Application_Form_Registration(array(
            'action' => $this->view->baseUrl('user/add'),
            'method' => 'post',
        ));
    }

    /**
     * @param array $values
     * @return Zend_Auth_Adapter_DbTable
     *
     */
    private function _getAuthAdapter(array $values)
    {
        $authAdapter = new Ahs_Auth_Adapter_DbTable();
        $authAdapter->setIdentity($values['email'])
                    ->setCredential($values['password']);

        return $authAdapter;
    }

    /**
     * @param string $titleTranslationKey
     * @return Zend_View
     *
     */
    private function _getView($titleTranslationKey)
    {
        $translate = Zend_Registry::get('Zend_Translate');

        $view = $this->view;
        $view->title = $translate->_($titleTranslationKey);
        $view->headTitle($view->title);
        $view->headLink()
             ->appendStylesheet($view->placeholder('baseUrlStyles') . 'main.css', 'all');

        return $view;
    }

}
